<template>
  <div class="classificationDetails h100">
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      :stepConfig="stepConfig"
      :moreBtnArr="moreBtnArr"
      showStep
      showTopTitle
      :showMore="showMore"
      :creatInfo="formData"
    >
      <template slot="editPageTitle">
        <i class="el-icon-document TitleImg"></i>
        分级分项验收单
      </template>
      <div class="orderTitle">
        <div v-show="!showInput" class="name">
          <span style="color: red"></span>
          <span>{{ orderTitle }}</span>
          <el-link
            v-show="!baseAttachBtn"
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input" :class="{remindColor:!userInput}">
          <el-input
            type="text"
            v-model="orderTitle"
            @blur="loseFocus"
            @change="userInputTitle"
            placeholder="请输入名称"
            clearable
            ref="mark"
          >
            <template slot="prepend" style="color: red">标题</template>
          </el-input>
        </div>
      </div>
      <el-collapse v-model="activeNames">
        <el-collapse-item name="1">
          <template slot="title">基本信息</template>
          <editForm :formConfig="basicConfig" ref="basicForm" :formData="formData">
            <template #orderCode="{ editFormInfo }">
              <div class="input-link">
                <el-input
                  size="mini"
                  :readonly="true"
                  v-model="editFormInfo.orderCode"
                  disabled
                  @click.native="
                    showOrder()
                  "
                ></el-input>
              </div>
            </template>
          </editForm>

          <div class="attachConten">
            <div class="attachTitle">作业表单:</div>
            <div class="tebleDiv">
              <editTableNew
                :tableSetting="workListStting"
                @handleClickAdd="addWorkList"
                showOperate
                :hideBtn="baseAttachBtn"
                ref="workListTable"
              ></editTableNew>
            </div>
          </div>
          <div class="attachConten">
            <div class="attachTitle">附件:</div>
            <div class="tebleDiv">
              <attachFormNew
                style="width: 60%"
                :disabled="baseAttachBtn"
                :attachSetting="attachSetting"
                isDelete
                multiple
                ref="attachForm"
              ></attachFormNew>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </editPageNew>
    <dialogPublic
      :title="'选择作业表单'"
      :show.sync="showWorkList"
      @doSubmit="selectWorkList"
      @doClose="() => (showWorkList = false)"
      appendTobody
      fullscreen
    >
      <workList ref="workList" v-if="showWorkList" :formData="formData" />
    </dialogPublic>
    <dialogPublic
      title="作业表单详情"
      :show.sync="showWorkListDetails"
      @doClose="() => (showWorkListDetails = false)"
      appendTobody
      fullscreen
      noFootBtn
    >
      <workListDetails ref="workListDetails" v-if="showWorkListDetails" :rowData="rowData" />
    </dialogPublic>
  </div>
</template>
<script>
import {
  saveOrUpdate, //新增分级分项验收单\保存分级分项验收单
  getDetailsApi, //获取分级分项验收单详情
  deleteApi, //删除分级分项验收单
  getWorkListDetailsApi //根据作业表单id查询详情
} from "@/api/orderManagement/classification";
import workList from "./workList"; //大修工单列表页
import workListDetails from "./workListDetails"; //作业列表详情
export default {
  components: { workList, workListDetails },
  data() {
    return {
      userInfo: this.$store.getters.userInfo,
      activeNames: ["1"], //
      editFormData: { status: "" },
      creatInfo: {},
      rowData: {},
      hideBtn: false,
      showInput: false,
      showMore: false,
      showWorkList: false,
      showWorkListDetails: false,
      changeType: "",
      parameterList: [],
      chooseData: [],
      tempTableData: [], //临时设备参数表格数据
      moveData: {},
      submitUser: [],
      deptOption: [],
      userOption: [],
      workerList: [],
      basicConfig: {
        itemArr: [
          {
            type: "text", //device\deviceClassify
            label: "分级分项名称",
            prop: "name",
            required: true,
            disabled: true,
            span: 8
          },
          {
            type: "select",
            label: "专业",
            prop: "major",
            selectOption: this.$store.getters["dirtData"]("common_major"),
            formatter: val => {
              return this.$store.getters["fineDirtDataName"](
                "common_major",
                val
              );
            },
            required: true,
            disabled: true,
            span: 8
          },
          {
            type: "select",
            label: "验收级别",
            prop: "level",
            selectOption: this.$store.getters["dirtData"]("order_level"),
            formatter: val => {
              return this.$store.getters["fineDirtDataName"](
                "order_level",
                val
              );
            },
            required: true,
            disabled: true,
            span: 8
          },
          {
            // type: "text", //device\deviceClassify
            label: "大修工单",
            prop: "orderCode",
            trigger: "change",
            required: true,
            span: 8
          },
          {
            label: "现场负责人",
            prop: "joberName", //多选时，字段要为数组类型
            propArr: "joberArr",
            idsStr: "jober",
            multiple: false, //是否多选
            isOutOrg: 0, //是否是外单位
            allowCreate: true, //是否允许创建条目
            option: [], //当前选中的项
            type: "user-select", //类型
            trigger: "change",
            methods: obj => {},
            required: true,
            span: 8
          },
          {
            label: "项目描述",
            prop: "context",
            type: "textarea",
            maxlength: "500",
            required: true,
            disabled: true,
            span: 24,
            rows: 4
          },
          {
            label: "验收标准",
            prop: "contextStandard",
            type: "textarea",
            maxlength: "500",
            disabled: true,
            required: true,
            span: 24,
            rows: 4
          },
          {
            label: "验收记录",
            prop: "recored",
            type: "textarea",
            maxlength: "500",
            required: true,
            span: 24,
            rows: 4
          }
        ]
      },
      /* 作业表单 */
      workListStting: {
        btnArr: ["add"], //"edit",
        data: [],
        select: false,
        addMethons: true,
        maxHeight: "100%",
        hideBtn: false,
        column: [
          {
            label: "表单编号",
            prop: "formCode",
            type: "text",
            textAlign: "center"
          },
          {
            label: "表单名称",
            prop: "formName",
            textAlign: "center",
            type: "text"
          }
        ],
        buttonArr: [
          {
            name: "详情",
            isShow: (row, index) => {
              return true;
            },
            methods: (row, index) => {
              this.rowData = row;
              this.showWorkListDetails = true;
            }
          },
          {
            name: "删除",
            isShow: (row, index) => {
              return this.status == "DRAFT";
            },
            methods: (row, index) => {
              this.deletRow(row, index);
            }
          }
        ]
      },
      //附件设置
      attachSetting: {
        businessId: "", //单据的ID
        businessType: "base"
      },
      userInput: false,
      orderTitle: "",
      menuType: "",
      pageType: "",
      status: "",
      formData: {},
      orderStatus: ["DRAFT", "ARCHIVED"]
    };
  },
  computed: {
    rightBtnArr() {
      let arr = [
        {
          text: "保存",
          icon: "el-icon-check",
          hide:
            ["details", "query", "perform"].includes(this.pageType) ||
            ["ARCHIVED"].includes(this.status),
          methods: () => {
            this.doSubmit("save");
          }
        },
        {
          text: "提交",
          icon: "el-icon-position",
          hide:
            ["perform", "details", "query"].includes(this.pageType) ||
            ["ARCHIVED"].includes(this.status),
          methods: () => {
            this.doSubmit("submit");
          }
        }
      ];
      return arr;
    },
    stepConfig() {
      let step = this.orderStatus.indexOf(this.status);
      let obj = {
        nowStep: parseInt(step), //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
        stepItem: ["草稿", "已结束"]
      };
      return obj;
    },
    moreBtnArr() {
      let arr = [
        {
          text: "操作记录",
          methods: () => {
            this.$refs.editPage.showOperate();
          }
        }
      ];
      return arr;
    },
    baseAttachBtn() {
      if (this.status == "DRAFT" && this.pageType != "details") {
        return false;
      } else {
        return true;
      }
    }
  },
  watch: {
    status: {
      handler(val) {
        if (val == "") {
          this.showMore = false;
        } else {
          this.showMore = true;
        }
        if (val != "DRAFT") {
          let itemArr = [];
          //深度拷贝数组对象(可拷贝函数)
          $.extend(true, itemArr, this.basicConfig.itemArr);
          itemArr.map(i => (i.disabled = true));
          this.basicConfig.itemArr = itemArr;
        }
      }
    }
  },
  created() {},
  mounted() {
    this.init();
  },
  methods: {
    init() {
      /* 分级分项没有在列表页自己新建的功能 */
      let { id, pageType } = this.$route.query;
      this.pageType = pageType;
      if (id) {
        this.formData.id = id;
        //判断页面类型
        let haveJurisdiction = this.$store.getters["isBtnAuth"]("edit");
        this.pageType = haveJurisdiction ? "edit" : "details";
      }
      if (["query", "details"].includes(this.pageType)) {
        this.basicConfig.itemArr.map(i => (i.disabled = true));
      }
      this.getDetails();
    },
    //获取分级分项验收单基本信息
    getDetails(id) {
      let dataId = id ? id : this.formData.id;
      getDetailsApi(dataId).then(res => {
        let data = res.data;
        this.$refs.workListTable.setTableData(data.forms || []);
        this.orderTitle = data.title;
        //用户是否自定义了工单名
        if (
          ["", null].includes(this.orderTitle) ||
          this.orderTitle.match(/^[ ]*$/)
        ) {
          this.showInput = true;
        } else {
          this.userInput = true;
          this.showInput = false;
        }
        //初始化附件ID
        this.attachSetting.businessId = data.id;
        //初始化发现人
        let { jober, joberName, joberType } = data;
        data.joberArr = data.jober;
        let option = this.$utils.getOptionData(joberName, jober, joberType);
        //设置发现人的Option
        this.$refs.basicForm.setItemOption("joberName", option);
        this.formData = data;
        setTimeout(() => {
          /* 避免setItemOption跟watch status 里面对this.basicConfig.itemArr起冲突，导致现场负责人显示不正常 */
          this.status = data.status;
        }, 100);
      });
    },
    async doSubmit(type) {
      //新增或者草稿状态时，保存缺陷-基本信息，提交缺陷-基本信息
      let data = await this.$refs.basicForm.getFormData();
      let workList = (await this.$refs.workListTable.getTableData()) || [];
      let workListArr = [];
      workList.map(i => {
        let obj = {
          formId: i.formId,
          gradeId: this.formData.id
        };
        workListArr.push(obj);
      });
      data.forms = workListArr;
      if (type == "save") {
        data.status = "DRAFT";
      } else if (type == "submit") {
        data.status = "ARCHIVED";
      }
      delete data.joberArr;
      data.title = this.orderTitle;
      if (data.title) {
        saveOrUpdate(data).then(res => {
          this.$utils.updateStorage();
          this.$message.success("操作成功！");
          if (this.pageType == "add") {
            this.pageType = "edit";
            this.formData.id = res.data;
            this.attachSetting.businessId = res.data;
            if (type == "submit") {
              this.$utils.addOperateLog(
                this.formData.id,
                "新增并提交-分级分项验收单"
              );
            } else {
              this.$utils.addOperateLog(
                this.formData.id,
                "新增-分级分项验收单"
              );
            }
          } else {
            this.$utils.addOperateLog(this.formData.id, "修改-分级分项验收单");
          }
          // if (type == "submit") {
          //   this.changeData();
          // }
          this.getDetails(res.data);
          this.saveAttachFile();
          //更新列表页的数据
        });
      } else {
        this.$message.warning("标题不能为空");
      }
    },
    // changeData() {
    //   let arr = this.orderStatus;
    //   let location = arr.indexOf(this.status);
    //   this.formData.status = arr[location + 1];
    //   this.status = arr[location + 1];
    // },
    saveAttachFile() {
      this.$refs.attachForm.save();
    },
    //选择作业表单
    async selectWorkList() {
      let data = this.$refs.workList.getSelectData();
      let selectData = [];
      data.map(i => {
        let { id, code, name, major } = i;
        let obj = {
          formCode: code,
          formId: id,
          formName: name,
          major
        };
        selectData.push(obj);
      });
      this.$refs.workListTable.setTableData(selectData);
      this.showWorkList = false;
    },
    inputChange(val) {
      this.currentKeys = val;
    },
    //用户输入工单标题
    userInputTitle(val) {
      if (val) {
        this.userInput = true;
      } else {
        this.userInput = false;
      }
    }, //失去焦点
    loseFocus() {
      if (
        ["", null].includes(this.orderTitle) ||
        this.orderTitle.match(/^[ ]*$/)
      ) {
        this.$message.warning("标题不能为空！");
      } else {
        this.showInput = false;
      }
    },
    //编辑标题
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
    //新增作业表单
    addWorkList(data, hadData) {
      this.showWorkList = true;
    },
    //删除表格的数据
    async deletRow(row, num) {
      let listArr = [];
      //获取当前作业准备的表格信息，不进行校验
      let workListData = await this.$refs.workListTable.getTableData(false);
      workListData.map((i, index) => {
        if (index != num) {
          i.editable = true;
          listArr.push(i);
        }
      });
      this.$refs.workListTable.setTableData(listArr);
    },
    //显示大修工单详情
    showOrder() {
      let form = {
        pageType: "ditails",
        id: this.formData.orderId,
        status: "IN_EXECUTE"
      };
      let { href } = this.$router.resolve({
        path: "/orderManagement/overhaul/details",
        query: form
      });
      window.open(href, "_blank");
    }
  }
};
</script>
<style lang="less" scoped>
.classificationDetails {
  // overflow: hidden;

  background-color: #ffffff;
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .attachConten {
    display: flex;
    flex-flow: wrap nowrap;
    .redPoint {
      color: red;
    }
    .attachTitle {
      width: 120px;
    }
    .tebleDiv {
      width: 100%;
    }
  }
  // .orderTitle {
  //   /deep/.el-input__inner {
  //     border: none;
  //     font-size: 16px;
  //     font-weight: bolder;
  //   }
  //   /deep/.el-input.is-disabled .el-input__inner,
  //   /deep/.el-range-editor.is-disabled input,
  //   /deep/.el-textarea.is-disabled .el-textarea__inner {
  //     background-color: rgba(252, 252, 252, 0);
  //   }
  // }
  .orderTitle {
    height: 60px;
    margin: 0 0 10px 0;
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 600px;
      height: 40px;
      line-height: 40px;
    }
    .remindColor {
      /deep/.el-input__inner {
        border: 1px solid red !important;
      }
    }
  }
  .attachConten + .attachConten {
    margin-top: 15px;
  }
  .input-link /deep/.el-input__inner {
    cursor: pointer;
    color: royalblue;
  }
}
</style>